package dsx.starter;

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Config {
	private static String configFile = "config.xml";
	private static String configDir = "conf/";
	private static ArrayList<String> configList = null;

	public static String get(String sectionName, String fieldName)
			throws Exception {
		try {
			ArrayList<String> confLst = getConfigFileList();
			if (confLst != null) {
				for (int h = 0; h < confLst.size(); h++) {
					NodeList sections = getNodeList(confLst.get(h), sectionName);
					for (int i = 0; i < sections.getLength(); i++) {
						NodeList fields = ((Element) sections.item(i))
								.getElementsByTagName(fieldName);
						if (fields.getLength() > 0)
							return fields.item(0).getTextContent();
					}
				}
			}
			throw new Exception("Node not exist.");
		} catch (Exception ex) {
			return null;
		}
	}

	private static NodeList getNodeList(String filePath, String tagName)
			throws Exception {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document document = db.parse(new File(filePath));
		Element root = document.getDocumentElement();
		return root.getElementsByTagName(tagName);
	}

	private static ArrayList<String> getConfigFileList() throws Exception {
		if (configList == null) {
			configList = new ArrayList<String>();
			File file = new File(configFile);
			if (file.exists())
				configList.add(configFile);
			getFileList(configDir, configList);
		}
		return configList;
	}

	private static void getFileList(String strPath, ArrayList<String> fileList)
			throws Exception {
		File dir = new File(strPath);
		File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				String fileName = files[i].getName();
				if (files[i].isDirectory()) { // 判断是文件还是文件夹
					getFileList(files[i].getAbsolutePath(), fileList); // 获取文件绝对路径
				} else if (fileName.endsWith("xml")) { // 判断文件名是否以.xml结尾
					fileList.add(files[i].getAbsolutePath());
				} else {
					continue;
				}
			}
		}
	}

}
